/*
 * @Author: liangbo
 * @Date: 2020-05-12 14:32:44
 * @LastEditTime: 2020-06-08 10:41:12
 * @LastEditors: Please set LastEditors
 * @Description: 用户控制器
 * @FilePath: \tuyibo\servers\api\user.js
 */
const path = require('path')
const express = require('express');
const user_router = express.Router();
const RQ = require('request-promise')
const cfg = require('../config')
const db = require('../models')
const auth = require('../comm/auth')
const comm = require('../comm')
const log4js = require('../config/log4js').log4js
const logger = log4js.getLogger('api-user');
const crypto = require('crypto')

// 用户更改信息
user_router.post('/updateUserInfo', async (req, res) => {
  var id=req.body.id;
  var change={
    nickname:req.body.nickname,
    mobile:req.body.mobile,
    email:req.body.email,
    sex:req.body.sex,
  }
  var where={where:{id}}
  var result=await db.user.updateUser(change,where)
  res.json(result)
})
// 修改性别
user_router.post('/updateSex', async (req, res) => {
  var id=req.body.id;
  var sex=req.body.sex;
  var change={sex}
  var where={where:{id}}
  var result=await db.user.updateUser(change,where)
  res.json(result)
})
// 修改手机号
user_router.post('/updatePhone', async (req, res) => {
  var id=req.body.id;
  var mobile=req.body.mobile;
  var change={mobile}
  var where={where:{id}}
  var result=await db.user.updateUser(change,where)
  res.json(result)
})
// 修改邮箱
user_router.post('/updateEmail', async (req, res) => {
  var id=req.body.id;
  var email=req.body.email;
  var change={email}
  var where={where:{id}}
  var result=await db.user.updateUser(change,where)
  res.json(result)
})
// 修改昵称
user_router.post('/updateNickname', async (req, res) => {
  var id=req.body.id;
  var nickname=req.body.nickname;
  var change={nickname}
  var where={where:{id}}
  var result=await db.user.updateUser(change,where)
  res.json(result)
})
// 修改头像
user_router.post('/updateAvatar', async (req, res) => {
  var id=req.body.id;
  var avatar=req.body.avatar;
  var info=await db.user.find_byid(id)
  var change={avatar}
  var where={where:{id}}
  if(info.avatar){
    comm.delete_imgage( path.join(process.cwd(), "static/images/",info.avatar ))
  }
  var result=await db.user.updateUser(change,where)
  res.json(result)
})


// 获取用户信息
user_router.post('/loadUserInfoByUid', async (req, res) => {
  // req.cookie={};
  // const cookieStr=req.headers.cookie;
  // cookieStr.split(';').forEach(item=>{
  //   if(!item){
  //     return
  //   }
  //   const arr=item.split('=')
  //   console.log(arr)
  //   const key=arr[0]
  //   const val =arr[1]
  //   req.coolie[key]=val
  // })
  var user_id=req.body.id
  let info=await db.user.findOne_byid(user_id)
  res.json(info)
})
//登录
user_router.post('/login', async (req, res) => {

  let data = req.body
  data.app = cfg.reg_app
  //通过服务去查找
  let loginres = await RQ({uri: `${process.env.AUTH_URL}/auth/login`,method: 'POST', json: true,
    rejectUnauthorized:false,
    headers: { "content-type": "application/json" },
    body:data
  }).then( (body, err) => { return body }).catch(function (err) {
    console.log(err)
    return "error"
  });

  if( loginres === "error" ){
    return res.json({"code":500})
  }
  if( loginres.code == 404 ){
    return res.json({"code":404})
  }else if( loginres.code == 500 ){
    return res.json({"code":500})
  }
  let body = loginres.data
  let uid = body.id
  let mobile = body.mobile
  let u = await db.user.findOne({ attributes: ['id', 'nickname','avatar'], where: { "base_user_id": uid } })

  //如果本地没有用户？
  if(u == null) {
    let nickname = `${mobile.substr(0,3)}**${mobile.substr(-3)}`
    u = await db.user.create({'nickname': nickname, 'mobile':mobile, 'base_user_id':uid, 'base_reg_from':body.regfrom}).then(function(task) {
      console.log("new user created")
      return task.dataValues
    }).catch(function(error) {
        console.log("innser user DB error", error)
        return null
    })
  }

  auth.login_user(req, u)
  res.json({"code":200,"userid":u.id,"name":u.nickname,"avatar":u.avatar})
})

//注销
user_router.post('/logout',async (req, res)=>{
  auth.logout_user(req)
  res.json({"code": 200})
})

//使用微信登录
user_router.get('/wxlogin', async (req, res)=>{
  let code = req.query.code
  let url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${cfg.weixin.OPEN_APPID}&secret=${cfg.weixin.OPEN_SECRET}&code=${code}&grant_type=authorization_code`
  let loginres = await RQ({uri: url,method: 'POST',json: true}).then( res => { return res })
  logger.info(`get access_token=>${JSON.stringify(loginres)}`)

  if( loginres.errcode !== undefined ){
    return res.send("登录失败")
  }else {
    let access_token = loginres.access_token
    let openid = loginres.openid
    let unionid = loginres.unionid !== undefined ? loginres.unionid : null
    let umodel = await db.user.find_wx_openid(openid, unionid)
    logger.info(`find_wx_openid umodel=>${umodel==null}`)

    if( umodel == null ){
      url = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}`
      let userinfo = await RQ({uri: url, method: 'GET',json: true}).then( res => { return res })
      let username = userinfo.nickname
      let province = userinfo.province
      let country = userinfo.country
      let city = userinfo.city
      let sex = userinfo.sex == 1 ? "男" : "女"
      let ip = comm.getIP(req);
      let headimgurl = userinfo.headimgurl
      let avatar_name = ''
      if(headimgurl){
        try{
            let savePATH = path.join(process.cwd(), 'static/avatar')
            if (!comm.fsExistsSync(savePATH)) {
              comm.mkdirsSync(savePATH)
            }
            avatar_name = openid
            savePATH = path.join(savePATH, avatar_name+".jpg") 
            let img = await comm.download_image(headimgurl, savePATH)
            if(img.status === false){
              logger.error('写入用户头像失败', err);
            }
        }catch(err){
          avatar_name = ''
          logger.error('获取用户头像失败', err)
        }
      }
      //写到base_user通用数据库
      // url = `${config.auth_url}/adduser`
      // let adddata = {}
      // let userinfo = await RQ({uri: url, method: 'POST',json: true,headers: { "content-type": "application/json" }, body:adddata}).then( res => {
      //   return res
      // })
      //写到数据库
      umodel = await new Promise ((resolve) => {
        db.user.create({'nickname': username, 'sex':sex, 'avatar':avatar_name, 'province': province,'city':city, 'register_ip': ip,
          'country': country, 'register_date':Date.parse(new Date()) / 1000, 'wx_openid': openid,'wx_unionid': unionid}).then(function(task) { //userinfo.subscribe
            logger.info("new user created")
              resolve(task.dataValues)
          }).catch(function(error) {
            logger.info("innser DB error", error)
              resolve("error")
          })
      }).catch(function(error) {
        logger.error("innser DB error", error)
        resolve("error")
      })

      if( umodel == null || umodel == 'error'){
        return res.send('用户操作失败')
      }
    }
    let reskey = 'wxlogin_'+ umodel.id
    comm.redis.set(reskey, JSON.stringify(umodel));
    comm.redis.expire(reskey, 180) 

    let wid = unionid !== null ? unionid : openid
    if( umodel.base_user_id == null ){
      res.redirect(`/user/wxlogin?action=bind_mobile&wid=${wid}&uid=${umodel.id}&name=${umodel.nickname}&avatar=${umodel.avatar}`)
    }else{
      res.redirect(`/user/wxlogin?action=close&wid=${wid}&uid=${umodel.id}&name=${umodel.nickname}&avatar=${umodel.avatar}`)
    }
  }
})

//验证是否登录成功
user_router.get('/check',  async (req, res)=>{
  let id = req.query.id
  let getv = await comm.redget('wxlogin_'+ id);
  if( getv !== null ){
    auth.login_user(req, JSON.parse(getv))
    comm.redis.del('wxlogin_'+ id)
    res.json({"status":1})
  }else{
    res.json({"status":0})
  }  
})

//绑定手机号
user_router.post('/bind_mobile',  async (req, res)=>{
  let result = { 'code': 500, 'msg':'error' }
  if( req.session.loginUser == undefined ){
      result['code'] = 502
      return res.json(result)
  }

  let [wid = '', uid = '', checkcode = null, password = null, mobile = null] = [req.body.wid, req.body.uid, req.body.checkcode, req.body.password, req.body.mobile]
  if(mobile==null || checkcode ==null||password==null){
      result['code'] = 400
      return res.json(result)
  }
	let sessionkey = req.cookies['connect.sid']
	sessionkey = crypto.createHash('md5').update(sessionkey).digest("hex")  

  let sendkey = await comm.redget(sessionkey);
  if(sendkey==null){
      result['code'] = 503
      return res.json(result)
  }

  if( req.session.loginUser.id != uid){
      result['code'] = 404
      return res.json(result)
  }

  let user = await db.user.find_byid(uid)
  if(user==null){
      result['code'] = 404
      return res.json(result)
  }

  let user_wid = user.wx_unionid != null ? user.wx_unionid : user.wx_openid
  if( wid != user_wid){
    result['code'] = 404
    return res.json(result)
  }

  let keys = sendkey.split('|')
  let key = keys[0]
  let num = keys[1]
  if(key != checkcode){
    result['code'] = 504
    result['msg'] = "codeerr"
    return res.json(result)
  }

  if(num != mobile){
    result['code'] = 505
    result['msg'] = "codeerr"
    comm.reds.del(req.cookies.session)
    return res.json(result)
  }

  //添加中心用户服务器用户
  let regres = await RQ({uri: `${process.env.AUTH_URL}/add-user`,method: 'POST', json: true,
    rejectUnauthorized:false,
    headers: { "content-type": "application/json" },
    body:{"mobile": mobile,"app": cfg.reg_app,"password":password,"wx_uionid": user_wid }
  }).then( (body, err) => { return body }).catch(function (err) {
    logger.error(err)
    return {code:500}
  });

  logger.info(regres)

  if( regres.code == 500 ){
    result['code'] = 507
    return res.json(result)
  }

  //用户已经存在
  if( regres.data.code == 200 ){
    result['code'] = 600
    result['name'] = regres.data.regfrom
  }

  if( regres.data.code == 200 || regres.data.code == -1 ){
    //更新用户表
    let changestate = await db.user.update({ 'base_user_id': regres.data.userid,'mobile': mobile }, {  where: { id: uid } });
    if (changestate == null) {
      result['code'] = 507
      return res.json(result)
    } 
  }

  result = { 'code': 200, 'msg':'ok' }
  return res.json(result)
})


module.exports = user_router